package com.kitty.game.activity.service.other;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.ActivityDataPool;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.model.product.ZDHuFaSet;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.ReqTelePort;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.map.service.MapService;
import com.kitty.game.mirror.model.FightMirror;
import com.kitty.game.mirror.model.MirrorFightParam;
import com.kitty.game.mirror.model.RoleMirror;
import com.kitty.game.mirror.service.FightMirrorService;
import com.kitty.game.npc.message.RespAutoWalk;
import com.kitty.game.npc.message.RespNpcContent;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.rank.service.handler.ZhengDaoRankHandler;
import com.kitty.game.role.model.Role;
import com.kitty.game.school.model.SchoolSet;
import com.kitty.game.school.service.SchoolService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.zhangmen.RespMasterInfo;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
//后加
import java.util.Collection;
import java.util.HashMap;
//import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**证道殿处理类*/
@Component
public class ZhengDaoDianHandler extends FightActivityHandler {
    private static final int MAPID = 29002;

    private static final String MEMBER_POLAR_NOT_SAME = "#Y{0}#n不是本门弟子，无法进入证道殿！[离开]";
    private static final String LEVEL_NOT_ENOUGH = "你年岁尚轻，勤学苦练之后再来找我吧！[离开]";
    private static final String LEVEL_MORE = "道友功力如此高深，此等小事无需劳驾。[离开]";
    private static final String IN_TEAM = "以多欺少，即便得胜亦是不武，还是一个人再来挑战我吧。[离开]";
    private static final String WIN_REMAIN_COUNT_NOT_ENOUGH = "你今日已战胜过护法，还是明天再来吧。[离开]";
    private static final String FAIL_ONE = "你今日已经证道过了，但若上交一枚#R证道魂#n我会考虑再指点你一次#R并在指点时稍稍放水#n。[上交证道魂/"+ NpcButton.FIGHT_TO_ZHENGDAOHUFA_ITEM.getKey() + "][算了/离开]";
    private static final String REMAIN_COUNT_NOT_ENOUGH = "你今日已证道多次，还是明天再来吧。[离开]";
    private static final String SEX_NOT_SAME = "你我男女有别，岂可乱了礼数！[离开]";
    private static final String FIGHT_SELF = "只有不断的超越自己，才能成为真正的强者！[我要超越自己/"+ NpcButton.BEYONG_ZHENGDAOHUFA.getKey()+"][知足常乐，我已满足了/离开]";
    private static final String IN_FIGHT = "这会儿正忙着呢，有什么事稍后再说。[离开]";
    private static final String NO_FIGHT_PET = "你还没有准备好参战宠物，这样打败你会说我胜之不武。[离开]";
    private static final String NO_ITEM = "你身上没有证道魂，如何上交？[离开]";
    private static final String FIGHT_WIN = "我#R{0}{1}#n果然人才辈出，真是让人欣慰！此刻起这#R护法#n之位就属于你了！[离开]";
    private static final String FIGHT_WIN_SELF = "恭喜你成功超越自我！";
    private static final String FIGHT_FAIL = "你还是先回去勤加练习再来吧！[离开]";
    private static final String HUFA_MESSGAE = "大家好，我是新晋护法。";
    private static final String ITEM_MESSAGE = "听说证道殿内各护法在收集证道魂，也许上交此物可以让护法#R再给我一次挑战的机会并偷偷放水#n。不过直接使用貌似会得到一些道行和武学，要怎么办呢？[上交换得1次指点机会/" + NpcButton.GOTO_FIGHT_TO_ZHENGDAOHUFA_ITEM.getKey()+"][直接使用/"+NpcButton.USE_ZHENGDAO_ITEM.getKey()+"][再想想/离开]";
    private static final String ITEM_DEST_TEMPLATE = "#P|证道殿({0},{1})::证道殿|E=我要挑战你（{2}—{3}级可挑战）@P{4}系掌门|M=进入证道殿#P";
    private static final String NO_ITEM_USE = "你身上没有证道魂";

    /**从传入map中获得对应数据*/
    public void loadCommonSet(Map<String ,String> commonSetMap) {
        String value = commonSetMap.get("zheng_dao_dian_set");
        List<ZDHuFaSet> zdHuFaSets = Json.fromJsonAsList(ZDHuFaSet.class, value);

        Map<Integer, ZDHuFaSet> zdHuFaSetMap = new HashMap<>();
        for (ZDHuFaSet zdHuFaSet : zdHuFaSets) {
            zdHuFaSetMap.put(zdHuFaSet.getNpcId(), zdHuFaSet);
        }
        ActivityDataPool.zdHuFaSetMap = zdHuFaSetMap;

        for (ZDHuFaSet zdHuFaSet : zdHuFaSets) {
            NPC npc = SpringUtils.getMapService().getNpc(zdHuFaSet.getNpcId());
            npc.setTitle(zdHuFaSet.getTitle());
            npc.setPolar(zdHuFaSet.getPolar());
        }
    }

    public ZDHuFaSet getZDHuFaSet(int npcId) {
        return ActivityDataPool.zdHuFaSetMap.get(npcId);
    }

    /**进入证道殿*/
    public void enterZhengDaoDian(Role role, NPC npc) {
        /**组队时，判断是否队员与队长职业是否相同，不相同时不能组队进入*/
        if (teamService.isInTeam(role)) {
            Team team = teamService.getTeam(role.getRoleId());
            String names = teamService.checkMember(team, memberRole -> memberRole.getPolar() != role.getPolar());
            if (names != null) {
                String content = MessageFormat.format(MEMBER_POLAR_NOT_SAME, names);

                if (npc != null) {
                    SpringUtils.getBean(ZhangMenHandler.class).sendNpcContent(role, npc, content);
                } else {
                    teamService.pushMessage(role, new RespMsg(content.replace(Const.LEAVE_BUTTON, "")));
                }

                return ;
            }
        }


        /**获得进入的位置*/
        ReqTelePort reqTelePort = new ReqTelePort();
        reqTelePort.setMapId(MAPID);
        reqTelePort.setX(67);
        reqTelePort.setY(46);
        SpringUtils.getMapService().changeMap(role, reqTelePort);
    }

    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        return bossNpc.getContent();
    }

    @Override
    public void sendNpcContent(Role role, NPC bossNpc, String content) {
        RespNpcContent respNpcContent = SpringUtils.getNpcService().getRespNpcContent(role, bossNpc, content);
        SpringUtils.getNpcService().sendRespNpcContent(role, respNpcContent);
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        ZDHuFaSet zdHuFaSet = getZDHuFaSet(bossNpc.getId());
        if (zdHuFaSet == null) {
            /**正常不应该执行到这里*/
            new RuntimeException(MessageFormat.format("没有护法数据， npcId: {}, npcName: {}", bossNpc.getId(), bossNpc.getName()));
            return IN_FIGHT;
        }

        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }
        /**小于可挑战等级*/
        if (role.getLevel() < zdHuFaSet.getMinLevel()) {
            return LEVEL_NOT_ENOUGH;
        }
        /**大于可挑战等级*/
        if (role.getLevel() > zdHuFaSet.getMaxLevel()) {
            return LEVEL_MORE;
        }
        /**不可组队*/
        if (teamService.isInTeam(role)) {
            return IN_TEAM;
        }
        /**没有参战宠物*/
        if (SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role) == null) {
            return NO_FIGHT_PET;
        }
        /**性别不同*/
        if (role.getGender() != zdHuFaSet.getGender()) {
            return SEX_NOT_SAME;
        }

        /**胜利挑战次数达到上限*/
        if (SpringUtils.getActivityService().getRemainCount(role, ActivityType.ZHENG_DAO_DIAN_WIN) <= 0) {
            return WIN_REMAIN_COUNT_NOT_ENOUGH;
        }

        /**挑战失败次数达到上限*/
        if (SpringUtils.getActivityService().getRemainCount(role, ActivityType.ZHENG_DAO_DIAN_FAIL) <= 0) {
            return REMAIN_COUNT_NOT_ENOUGH;
        }

        /**挑战失败过时*/
        if (SpringUtils.getActivityService().getFinishCount(role, ActivityType.ZHENG_DAO_DIAN_FAIL) >= 1) {
            if (role.getTalk().popChooseParam("fight_zhengdaodianhufa_item_confirm") == null) {
                role.pushTempCache("fight_zhengdaodianhufa_item_confirm", true);
                return FAIL_ONE;
            } else if(SpringUtils.getEquipService().getCount(Const.ZHENGDAO_ITEM_NAME, true, role) <= 0){
                return NO_ITEM;
            }
        }

        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror != null) {
            /**挑战对象是自己时*/
            if (fightMirror.getRoleMirror().getUid() == role.getUid() && role.getTalk().popChooseParam("fight_zhengdaodianhufa_beyond_confirm") == null) {
                return FIGHT_SELF;
            }
        }

        return null;
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        /**使用证道魂时*/
        if (role.popTempCache("fight_zhengdaodianhufa_item_confirm") != null) {
            SpringUtils.getEquipService().delRoloEquip(Const.ZHENGDAO_ITEM_NAME, 1, true, role);
            role.pushTempCache(Const.FIGHT_MIRROR_PROP_RATE_KEY, 0.8);
        }

        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror == null) {
            /**没有人挑战成功过，则根据挑战玩家数据生成镜像*/
            fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        }
        bossNpc.setCreateTime(System.currentTimeMillis());

        MirrorFightParam mirrorFightParam = new MirrorFightParam((byte) getFightType(role), bossNpc.getId(), fightMirror);
        SpringUtils.getMirrorService().startFight(role, mirrorFightParam);
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_zhengdaodian;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {

    }

    @Override
    public void doFightWinForSingle(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        super.doFightWinForSingle(role, fightEndEvent, bossNpc);
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.ZHENG_DAO_DIAN_WIN, 1);

        /**替换护法数据*/
        FightMirror fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        FightMirror oldFightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        SpringUtils.getMirrorService().addFightMirror(fightMirror);
        ZDHuFaSet zdHuFaSet = getZDHuFaSet(bossNpc.getId());
        fightMirror.getRoleMirror().setTitle(zdHuFaSet.getTitle());
        fightMirror.getRoleMirror().setMessage(HUFA_MESSGAE);

        /**更新npc外观*/
        bossService.broadcastNpcUpdate(new GroupMapParam(role), bossNpc);

        /**挑战自己的时候不需要再发称号*/
        if (oldFightMirror == null || oldFightMirror.getRoleMirror().getUid() != role.getUid()) {
            SchoolSet schoolSet = SpringUtils.getBean(SchoolService.class).getShoolSet((byte) role.getPolar());
            MapService mapService = SpringUtils.getMapService();
            sendNpcContent(role, bossNpc, MessageFormat.format(FIGHT_WIN, mapService.getMap(schoolSet.getOuterMap()).getName(), mapService.getMap(schoolSet.getInnerMap()).getName()));

            Role oldRole = (oldFightMirror !=null ? SpringUtils.getPlayerService().getPlayerBy(oldFightMirror.getRoleMirror().getUid()) : null);
            /**旧的称号马上收回*/
            delOldTitle(oldRole, zdHuFaSet.getTitle());
            /**新的称号发放*/
            addTitle(role, bossNpc, zdHuFaSet.getTitle(), oldRole);

            /**更新排行榜*/
            if (oldFightMirror != null) {
                updateRank(oldFightMirror);
            }
        }else {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(FIGHT_WIN_SELF));
        }
    }

    private void updateRank(FightMirror fightMirror) {
        if (fightMirror == null) {return ;}
        int time = getTime(fightMirror);
        RoleMirror roleMirror = fightMirror.getRoleMirror();
        SpringUtils.getBean(ZhengDaoRankHandler.class).update(String.valueOf(roleMirror.getUid()), (byte)roleMirror.getPolar(), roleMirror.getLevel(), roleMirror.getPartyName(), roleMirror.getName(), (short)roleMirror.getIcon(), time);
    }

    private int getTime(FightMirror fightMirror) {
        if (fightMirror == null) {return 0;}
        return (int) ((System.currentTimeMillis() - fightMirror.getCreateTime()) / TimeUtil.ONE_SECOND);
    }

    /**收回旧称号*/
    private void delOldTitle(Role role, String title) {
        if (role == null) {return ;}
        SpringUtils.getRoleService().delTitle(role, title);
    }

    /**添加称号*/
    private void addTitle(Role role, NPC bossNpc, String title, Role oldRole) {
        /**发称号*/
        SpringUtils.getRoleService().addTitle(role, new TitleInfo(title, title));
    }

    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        /**暂时奖励，后面再调整。2倍刷道奖励*/
        giveReward(role, 2);
    }

    protected void giveReward(Role role, int rewardRate) {
        /**暂时奖励，后面再调整。*/
        int daohang = 150 * rewardRate;
        SpringUtils.getRoleService().addTao(role, daohang);

        int currPetId = role.getTempCache("fight_current_pet_id", 0);
        Pet pet = SpringUtils.getPetService().getPetById(currPetId, role);
        if (pet != null) {
            /**暂时奖励，后面再调整。*/
            int petWuxue = 2 * rewardRate;
            NutMap doubleStatus = role.getPropsStatus();
            int point = doubleStatus.getInt("pet");
            if (doubleStatus.getInt("petStatus") == 1 && point >= 4) {
                doubleStatus.setv("pet", point - 4);
                role.save();
                petWuxue = petWuxue * 2;
            }
            SpringUtils.getRoleService().addPetMatiral(role, pet, petWuxue);
        }
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {

    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.ZHENG_DAO_DIAN_FAIL, 1);
        NPC bossNpc = getBossNpc(fightEndEvent.getNpcId());
        sendNpcContent(role, bossNpc, FIGHT_FAIL);
        giveFailReward(role, fightEndEvent, bossNpc);
    }

    protected void giveFailReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        /**给证道魂*/
        if (SpringUtils.getActivityService().getFinishCount(role, ActivityType.ZHENG_DAO_DIAN_FAIL) <= 1) {
            SpringUtils.getEquipService().addMall(Const.ZHENGDAO_ITEM_NAME, true, role, 1);
        }
    }

    /**超越自己*/
    public void beyondSelf(Role role, NPC bossNpc) {
        role.getTalk().pushChooseParam("fight_zhengdaodianhufa_beyond_confirm", true);
        startFight(role, bossNpc);
    }

    /**查看护法信息*/
    public void viewHuFa(Role role, NPC npc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(npc.getId());

        RespMasterInfo respMasterInfo = null;
        if (fightMirror == null) {
            /**没有护法数据*/
            ZDHuFaSet zdHuFaSet = getZDHuFaSet(npc.getId());
            RoleMirror roleMirror = new RoleMirror();
            roleMirror.setIcon(npc.getIcon());
            roleMirror.setName(npc.getName());
            roleMirror.setTitle(zdHuFaSet.getTitle());
            roleMirror.setLevel(zdHuFaSet.getMinLevel());
            roleMirror.setMessage(HUFA_MESSGAE);
            respMasterInfo = new RespMasterInfo(role, roleMirror);
        } else {
            /**有护法数据*/
            respMasterInfo = new RespMasterInfo(role, fightMirror.getRoleMirror());
        }

        MessagePusher.pushMessage(role, respMasterInfo);
    }

    /**上交证道魂战斗*/
    public void fightUseItem(Role role, NPC bossNpc) {
        role.getTalk().pushChooseParam("fight_zhengdaodianhufa_item_confirm", true);
        startFight(role, bossNpc);
    }

    /**使用证道魂道具*/
    public void useZhengDaoHunItem(Role role, RoleEquip roleEquip) {
        RespNpcContent respNpcContent = new RespNpcContent();
        respNpcContent.setNpcName(role.getName());
        respNpcContent.setNpcId((int) role.getRoleId());
        respNpcContent.setContent(ITEM_MESSAGE);
        respNpcContent.setNpcIcon(role.getRoleIcon());
        MessagePusher.pushMessage(role, respNpcContent);
    }

    /**去上交证道魂*/
    public void gotoFightUseItem(Role role) {
        if (SpringUtils.getEquipService().getCount(Const.ZHENGDAO_ITEM_NAME, true, role) <= 0) {
            teamService.pushMessage(role, new RespMsg(NO_ITEM_USE));
            return ;
        }

        /**寻路到对应NPC*/
        ZDHuFaSet matchZDHuFaSet = getMatchZDHuFaSet(role);
        if (matchZDHuFaSet != null) {
            NPC npc = SpringUtils.getMapService().getNpc(matchZDHuFaSet.getNpcId());
            SchoolSet schoolSet = SpringUtils.getBean(SchoolService.class).getShoolSet((byte) role.getPolar());
            //#P|证道殿(61,29)::证道殿|E=我要挑战你（70—79级可挑战）@P木系掌门|M=进入证道殿#P
            String dest = MessageFormat.format(ITEM_DEST_TEMPLATE, npc.getX(), npc.getY(), matchZDHuFaSet.getMinLevel(), matchZDHuFaSet.getMaxLevel(), schoolSet.getTypeName());

            RespAutoWalk respAutoWalk = new RespAutoWalk();
            respAutoWalk.setTaskName("");
            respAutoWalk.setDest(dest);
            MessagePusher.pushMessage(role, respAutoWalk);
        }
    }

    private ZDHuFaSet getMatchZDHuFaSet(Role role) {
        Collection<ZDHuFaSet> values = ActivityDataPool.zdHuFaSetMap.values();
        for (ZDHuFaSet zdHuFaSet : values) {
            if (zdHuFaSet.getPolar() != role.getPolar()) {continue;}
            if (zdHuFaSet.getMinLevel() > role.getLevel()) {continue;}
            if (zdHuFaSet.getMaxLevel() < role.getLevel()) {continue;}

            return zdHuFaSet;
        }

        return null;
    }

    /**直接使用证道魂道具*/
    public void useItemDirect(Role role) {
        /**判断是否有证道魂道具*/
        if (SpringUtils.getEquipService().getCount(Const.ZHENGDAO_ITEM_NAME, true, role) <= 0) {
            teamService.pushMessage(role, new RespMsg(NO_ITEM_USE));
            return ;
        }
        /**扣除证道魂道具*/
        SpringUtils.getEquipService().delRoloEquip(Const.ZHENGDAO_ITEM_NAME, 1, true, role);

        /**获得对应的奖励*/
        giveReward(role, 1);
    }


    /**每隔一段时间检测更新，排行榜的守护时间。*/
    public void updateRank() {
        Set<Integer> npcIds = ActivityDataPool.zdHuFaSetMap.keySet();

        FightMirrorService fightMirrorService = SpringUtils.getBean(FightMirrorService.class);
        for (int npcId : npcIds) {
            FightMirror fightMirror = fightMirrorService.getFightMirror(npcId);
            if (fightMirror == null) { continue;}

            updateRank(fightMirror);
        }
    }
}
